﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace GreenPark
{
    public delegate int CallBack(ulong nTotal, ulong nDone);
    public delegate int FuncProcessData(string strDevInfo, uint nStrDevInfoLen, string strRecvInfo, uint nStrRecvInfo);

    public class Process
    {
        [DllImport("HDCP_Utils.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern string HDCP_Base64Decode(string pInputInfo, ref uint pSizeInput);
        [DllImport("HwDevComm.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern int HwDev_Execute(string pDevInfoBuf, int nDevInfoLen,
                                               IntPtr pSendBuf, int nSendLen,
                                               ref IntPtr pRecvBuf, ref uint pRecvLen,
                                               CallBack pFuncTotalDone);
        [DllImport("HwDevComm.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern int HwDev_Finish(ref IntPtr pRecvBuf);


        [DllImport("kernel32.dll")]
        public static extern IntPtr GlobalAlloc(int uFlags, int dwBytes);
        [DllImport("kernel32.dll")]
        public static extern IntPtr GlobalFree(IntPtr hMem);
        [DllImport("kernel32.dll")]
        public static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        public static extern bool GlobalUnlock(IntPtr hMem);


        static string GetDeviceInfo(String ipStr)
        {
            string devInfo;

            devInfo = "DeviceInfo( dev_id = \"1\" dev_type = \"HW_HDCP\" comm_type = \"ip\" ip_address = \"" + ipStr + "\")";
            return devInfo;

        }
        private static CallBack myCallBack;
        private static FuncProcessData myFuncProcessData;
        private static Mutex mut;
        private static long snNumber;
        private string selType;

        public static int HwDev_Execute(string pDevInfoBuf, int nDevInfoLen, string pSendBuf, int nSendLen, ref string pRecvBuf, ref uint pRecvLen, CallBack pFuncTotalDone)
        {
            int ret = 0;
            IntPtr dataPtr = IntPtr.Zero;
            byte[] data;
            IntPtr pRecvBuf2 = IntPtr.Zero;
            try
            {
                data = ASCIIEncoding.Default.GetBytes(pSendBuf);
                int dataLen = (int)data.Length;

                dataPtr = GlobalAlloc(0x0000, dataLen);
                if (dataPtr == IntPtr.Zero)
                    return -1;// (int)RetValue.ERR_RECG_NOT_ENOUGH_MEM;

                dataPtr = GlobalLock(dataPtr);
                if (dataPtr == IntPtr.Zero)
                    return -1;// (int)RetValue.ERR_RECG_NOT_ENOUGH_MEM;

                Marshal.Copy(data, 0, dataPtr, dataLen);



                ret = HwDev_Execute(pDevInfoBuf, pDevInfoBuf.Length, dataPtr, dataLen, ref  pRecvBuf2, ref  pRecvLen, pFuncTotalDone);
                pRecvBuf = Marshal.PtrToStringAnsi(pRecvBuf2);
                HwDev_Finish(ref pRecvBuf2);


            }
            catch (System.Exception e)
            {
                ret = -1;
                throw new OperationCanceledException(e.Message);

            }
            finally
            {
                GlobalUnlock(dataPtr);
                GlobalFree(dataPtr);
                data = null;
            }

            return ret;
        }

        static int BeCalled(ulong nTotal, ulong nDone)
        {
            return 0;
        }

        public static bool DeviceExists(string ip)
        {
            string devInfo, cmdStr, retStr;
            retStr = "";
            IntPtr ret = IntPtr.Zero;
            uint retlen = 0;
            devInfo = GetDeviceInfo(ip);
            cmdStr = "GetDeviceInfo()";
            myCallBack = new CallBack(BeCalled);
            int result;
            result = HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, myCallBack);

            if (result == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public static string getFaceData(string id)
        {
            string data = "";
            string ipadresi = "";
            foreach (Cihaz item in Program.Db.Cihazlar)
            {
                if (item.KayitKapisi)
                {
                    ipadresi = item.IpAdresi;
                    break;
                }
            }

            ulong startID = ulong.Parse(id);
            ulong endID = ulong.Parse(id);
            string devInfo, cmdStr, retStr;
            retStr = "";
            IntPtr ret = IntPtr.Zero;
            uint retlen = 0;
            //string ip_addr = Text;
            devInfo = GetDeviceInfo(ipadresi);

            for (ulong employeeID = startID; employeeID <= endID; employeeID++)
            {
                cmdStr = "GetEmployee(id=\"";
                cmdStr = cmdStr + employeeID.ToString() + "\")";
                ret = IntPtr.Zero;
                retlen = 0;
                HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, null);
                if (CommonFun.isCmdExecSuccess(retStr))
                {
                    data = retStr;
                }
            }
            return data;
        }

        public static void setFaceData(string facedata)
        {
            StringBuilder sb = new StringBuilder();
            foreach (Cihaz item in Program.Db.Cihazlar)
            {
                if (!item.KayitKapisi)
                {

                    string devInfo, cmdStr, retStr;
                    retStr = "";
                    IntPtr ret = IntPtr.Zero;
                    uint retlen = 0;
                    devInfo = GetDeviceInfo(item.IpAdresi);
                    cmdStr = facedata.Replace("Return(result=\"success\"", "SetEmployee(");

                    int result;
                    result = HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, null);

                    if (CommonFun.isCmdExecSuccess(retStr))
                    {
                        sb.Append("Cihaz : " + item.Tanim + "  " + " gönderildi ! \r\n");
                    }
                    else
                    {
                        sb.Append("Cihaz : " + item.Tanim + "  " + " gönderilemedi ! \r\n");
                    }
                }
            }
            MessageBox.Show(sb.ToString());
        }

        public static void AddCustomer(string id, string adi)
        {
            foreach (Cihaz item in Program.Db.Cihazlar)
            {
                if (item.KayitKapisi)
                {
                    string devInfo, cmdStr, retStr;
                    retStr = "";
                    IntPtr ret = IntPtr.Zero;
                    uint retlen = 0;

                    devInfo = GetDeviceInfo(item.IpAdresi);
                    cmdStr = "SetNameTable(" + id + "=\"" + adi + "\" " + ")";
                    int result;
                    result = HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, null);
                    if (CommonFun.isCmdExecSuccess(retStr))
                    {
                        MessageBox.Show("Kayıt gönderildi ! Yüz tanıtımına geçebilirsiniz.");
                        break;
                    }
                }
            }
        }

        public static void AddCustomer(Users usr)
        {
            foreach (Cihaz item in Program.Db.Cihazlar)
            {
                bool gonder = true;
                string devInfo, cmdStr, retStr;
                retStr = "";
                IntPtr ret = IntPtr.Zero;
                uint retlen = 0;
                //if (item.No == 1 && usr.Chz1 == KayitDurumu.Eklenecek)
                //{
                //    gonder = true;
                //}
                //else if (item.No == 2 && usr.Chz2 == KayitDurumu.Eklenecek)
                //{
                //    gonder = true;
                //}
                //else if (item.No == 3 && usr.Chz3 == KayitDurumu.Eklenecek)
                //{
                //    gonder = true;
                //}
                //else if (item.No == 4 && usr.Chz4 == KayitDurumu.Eklenecek)
                //{
                //    gonder = true;
                //}

                if (gonder)
                {
                    devInfo = GetDeviceInfo(item.IpAdresi);
                    cmdStr = "SetNameTable(" + usr.ID + "=\"" + usr.Adi + "\" " + ")";
                    int result;
                    result = HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, null);

                    if (CommonFun.isCmdExecSuccess(retStr))
                    {
                        switch (item.No)
                        {
                            case 1:
                                usr.Chz1 = KayitDurumu.Eklendi;
                                break;
                            case 2:
                                usr.Chz2 = KayitDurumu.Eklendi;
                                break;
                            case 3:
                                usr.Chz3 = KayitDurumu.Eklendi;
                                break;
                            case 4:
                                usr.Chz4 = KayitDurumu.Eklendi;
                                break;
                        }

                        LogYaz("Kayıt Eklendi ! " + usr.ID + " - " + usr.Adi);
                    }
                    else
                    {
                        switch (item.No)
                        {
                            case 1:
                                usr.Chz1 = KayitDurumu.Eklenecek;
                                break;
                            case 2:
                                usr.Chz2 = KayitDurumu.Eklenecek;
                                break;
                            case 3:
                                usr.Chz3 = KayitDurumu.Eklenecek;
                                break;
                            case 4:
                                usr.Chz4 = KayitDurumu.Eklenecek;
                                break;
                        }
                        LogYaz("Kayıt gönderilemedi ! " + usr.ID + " - " + usr.Adi);
                    }
                }

            }
        }

        static void LogYaz(string mesaj)
        {
            using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\log.txt", true))
            {
                sw.WriteLine("Tarih:" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
                sw.WriteLine(mesaj);
                sw.WriteLine("--------------------------------------------");
                sw.Close();
            }
        }

        public static void DeleteCustomer(Users usr)
        {
            foreach (Cihaz item in Program.Db.Cihazlar)
            {
                bool silinecek = false;
                ulong employeeID = ulong.Parse(usr.ID);
                string devInfo, cmdStr, retStr;
                retStr = "";
                IntPtr ret = IntPtr.Zero;
                uint retlen = 0;

                if (item.No == 1 && usr.Chz1 == KayitDurumu.Silinecek)
                {
                    silinecek = true;
                }
                else if (item.No == 2 && usr.Chz2 == KayitDurumu.Silinecek)
                {
                    silinecek = true;
                }
                else if (item.No == 3 && usr.Chz3 == KayitDurumu.Silinecek)
                {
                    silinecek = true;
                }
                else if (item.No == 4 && usr.Chz4 == KayitDurumu.Silinecek)
                {
                    silinecek = true;
                }

                if (silinecek)
                {
                    devInfo = GetDeviceInfo(item.IpAdresi);
                    bool flag = false;
                    cmdStr = "DeleteEmployee(id=\"";
                    cmdStr = cmdStr + employeeID.ToString() + "\")";
                    ret = IntPtr.Zero;
                    retlen = 0;
                    HwDev_Execute(devInfo, devInfo.Length, cmdStr, cmdStr.Length, ref retStr, ref retlen, null);
                    if (CommonFun.isCmdExecSuccess(retStr))
                    {
                        flag = true;
                    }
                    if (flag == true)
                    {
                        switch (item.No)
                        {
                            case 1:
                                usr.Chz1 = KayitDurumu.Silindi;
                                break;
                            case 2:
                                usr.Chz2 = KayitDurumu.Silindi;
                                break;
                            case 3:
                                usr.Chz3 = KayitDurumu.Silindi;
                                break;
                            case 4:
                                usr.Chz4 = KayitDurumu.Silindi;
                                break;
                        }

                        LogYaz("Kayıt Silindi ! " + usr.ID + " - " + usr.Adi);
                    }
                    else
                    {
                        switch (item.No)
                        {
                            case 1:
                                usr.Chz1 = KayitDurumu.Silinecek;
                                break;
                            case 2:
                                usr.Chz2 = KayitDurumu.Silinecek;
                                break;
                            case 3:
                                usr.Chz3 = KayitDurumu.Silinecek;
                                break;
                            case 4:
                                usr.Chz4 = KayitDurumu.Silinecek;
                                break;
                        }

                        LogYaz("Kayıt Silinemedi ! " + usr.ID + " - " + usr.Adi);
                    }
                }
            }
        }
    }
}
